package com.arpa.wms.controller;

import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.arpa.core.utils.collection.ListUtil;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.constant.StrConsts;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.wms.cache.WarehouseCache;
import com.arpa.wms.domain.consts.CodeConst;
import com.arpa.wms.domain.consts.NumConst;
import com.arpa.wms.service.IInboundService;
import com.arpa.wms.service.IOutboundService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>
 * Wms首页报表接口
 * </p>
 *
 * @author LEO
 * @since 2020-08-03
 */
@Api(tags = "首页图表")
@RestController
@RequestMapping(value = "/home", produces = "application/json;charset=UTF-8")
@Log4j2
public class HomeController {


    private final IInboundService iInboundService;
    private final IOutboundService outboundService;
    private final WarehouseCache warehouseCache;

    public HomeController(IInboundService iInboundService,
                          IOutboundService outboundService,
                          WarehouseCache warehouseCache
                          ) {
        this.iInboundService = iInboundService;
        this.outboundService = outboundService;
        this.warehouseCache = warehouseCache;
    }


    /**
     * 首页出库折线图数据
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "首页出库折线图数据", notes = "首页出库折线图数据")
    @GetMapping("lineData")
    public Result lineData(HttpServletRequest request) {
        try {
            //当前登录仓库
            List<String> warehouseCodes = UserUtil.getAuthorizeWarehouseCodes();
            List<String> shipmentCodes = UserUtil.getAuthorizeShipmentCodes();

//            DateTime firstDatetime = DateUtil.offsetWeek(new Date(),-1);
//            String fdt =  DateUtil.format(firstDatetime,"yyyy-MM-dd 23:59:59");
            //按时间、仓库分组获取入库数量
            List<Map<String, Object>> outbountCount = outboundService.outboundCount(warehouseCodes,shipmentCodes,UserUtil.getBranchCode());
            return generateBarDate(warehouseCodes,outbountCount);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 首页入库柱状图数据
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "首页入库柱状图数据", notes = "首页入库柱状图数据")
    @GetMapping("barData")
    public Result barData(HttpServletRequest request) {
        try {
            List<String> warehouseCodes = UserUtil.getAuthorizeWarehouseCodes();

            DateTime firstDatetime = DateUtil.offsetWeek(new Date(),-1);
            String fdt =  DateUtil.format(firstDatetime,"yyyy-MM-dd 23:59:59");
            //按时间、仓库分组获取入库数量
            List<Map<String, Object>> inbountCount = iInboundService.inboundCount(warehouseCodes,UserUtil.getAuthorizeShipmentCodes(),fdt);
            return generateBarDate(warehouseCodes,inbountCount);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    private Result generateBarDate(List<String> warehouseCodes, List<Map<String, Object>> countList) {

        Map<String, List<Map<String, Object>>> mapList = countList.stream()
                .collect(Collectors.groupingBy(r -> MapUtil.getStr(r, CodeConst.WAREHOUSE_CODE)));
        List<String> dateList = getDateList();

        List<Map<String, Object>>  barDate = new ArrayList<>();
        //新创建的账号还没有创建仓库登录时的处理
        if (IterUtil.isEmpty(warehouseCodes)) {
            Map<String, Object> returnMap = new HashMap<>();
            returnMap.put("name", StrUtil.EMPTY);
            returnMap.put("dateList", dateList);
            returnMap.put("dataList", new ArrayList<Object>(Arrays.asList(0,0,0,0,0,0,0)));
            barDate.add(returnMap);
            return Result.ok().data(barDate);
        }

        //创建完仓库的处理
        for (String warehouseCode : warehouseCodes) {
            Map<String, Object> returnMap = new HashMap<>();
            List<Object> dataList = new ArrayList<>();
            List<Map<String, Object>> warehouseList = MapUtil.get(mapList, warehouseCode, List.class);
            for (String date : dateList) {
                if (IterUtil.isNotEmpty(warehouseList)) {
                    List<Map<String, Object>> collect = warehouseList.stream().filter(e ->
                            StrUtil.equals(MapUtil.getStr(e, "dateStr"), date))
                            .collect(Collectors.toList());
                    if(IterUtil.isNotEmpty(collect)){
                        dataList.add(MapUtil.getDouble(ListUtil.getFirst(collect), "quantity"));
                    }else {
                        dataList.add(NumConst.NUM_ZERO);
                    }
                }else{
                    dataList.add(NumConst.NUM_ZERO);
                }
            }
            returnMap.put("name", warehouseCache.translate(warehouseCode));
            returnMap.put("dateList", dateList);
            returnMap.put("dataList", dataList);
            barDate.add(returnMap);
        }
        return Result.ok().data(barDate);
    }

    public List<String> getDateList(){
        List<String> dateList = new ArrayList<>();
        dateList.add(DateUtil.formatDate(DateUtil.offsetDay(DateUtil.date(), -6)));
        dateList.add(DateUtil.formatDate(DateUtil.offsetDay(DateUtil.date(), -5)));
        dateList.add(DateUtil.formatDate(DateUtil.offsetDay(DateUtil.date(), -4)));
        dateList.add(DateUtil.formatDate(DateUtil.offsetDay(DateUtil.date(), -3)));
        dateList.add(DateUtil.formatDate(DateUtil.offsetDay(DateUtil.date(), -2)));
        dateList.add(DateUtil.formatDate(DateUtil.offsetDay(DateUtil.date(), -1)));
        dateList.add(DateUtil.today());
        return dateList;
    }


}
